import sys
from playwright.sync_api import sync_playwright

def log_request_and_response(request, response):
    print(f"Request: {request.method} {request.url}")
    if request.post_data:
        print(f"Request Data: {request.post_data}")
    print(f"Response Status: {response.status}")
    #print(f"Response Data: {response.body()}")

def log_ws_messages(route, request):
    print(f"WebSocket request: {request.url}  {request.resource_type}")
    if request.resource_type == "websocket":
        print(f"WebSocket request: {request.url}")
    if "websocket" in request.url:
        # 拦截WebSocket的消息并记录
        ws = route.fetch(request)
        ws.on("framesent", lambda msg: print(f"wlh--Sent: {msg}"))
        ws.on("framereceived", lambda msg: print(f"wlh--Received: {msg}"))
    # 继续请求，以确保页面正常加载
    route.continue_()


    # Intercept WebSocket messages
def log_ws_messages(websocket):
    print(f"WebSocket connected to {websocket.url}")
    websocket.on("framereceived", lambda frame: print(f"WebSocket message received: {frame}"))
    websocket.on("framesent", lambda frame: print(f"WebSocket message sent: {frame}"))


def run(playwright):
    browser = playwright.chromium.launch(headless=False)  # headless=False 表示使用可视化浏览器
    context = browser.new_context()
    
    # 监听所有WebSocket连接
    #context.route("**/*", log_ws_messages)
    
    # 打开一个新的页面
    page = context.new_page()
    print("Navigating to the page...")


    # Add WebSocket event listener
    page.on("websocket", log_ws_messages)

    # 监听 response 事件，并且在获取到响应时与对应的请求一起打印
    page.on("response", lambda response: log_request_and_response(response.request, response))


    # 访问你想要监控WebSocket通信的页面
    # page.goto("https://www.raybet.lol/match/"+sys.argv[1],wait_until="load", timeout=6000000)  # 将此URL替换为目标网站
    # print("Page loaded")


    # 保持浏览器打开，等待手动操作
    page.wait_for_timeout(1000*60*60*24*5)  # 30秒后关闭浏览器

    #browser.close()

with sync_playwright() as playwright:
    run(playwright)


# 邮件 ， 任务，消息，终端，其他，通知，字典
# 邮件 ， 任务，消息，终端，其他，通知，字典


# 菜单资源 部门 sso应用 其他权限 企业 角色 用户权限 用户 日志

# 菜单资源  sso应用 其他权限 企业 角色   